<template>
  <view>
    <t-cell
      v-if="showCell"
      :title="title"
      arrow
      hover
      :note="labelModel"
      @click="onPicker"
    />

    <t-popup v-model="visibleModel" placement="bottom">
      <t-input
        v-model:value="keywords"
        placeholder="请输入单位名称搜索"
        @change="debounceSearch"
      >
        <template #suffix>
          <t-icon name="search" />
        </template>
      </t-input>
      <t-picker
        :value="pickData"
        :columns="columns"
        :title="title"
        cancelBtn="取消"
        confirmBtn="确认"
        @change="onPickerChange"
        @cancel="onDangerTypePickerCancel"
      >
        <!-- <t-picker-item :options="dangerTypeOptions" /> -->
      </t-picker>
    </t-popup>
  </view>
</template>

<script setup>
import { ref, defineProps, defineEmits } from "vue";
import { useVModel } from "@vueuse/core";
import { isBoolean } from "lodash-es";
import { getCompanyList } from "/api/common";
import { debounce } from "lodash-es";

const props = defineProps({
  value: {
    type: Array,
    default: [],
  },
  visible: {
    type: [String, Boolean],
    default: "",
  },
  label: {
    type: String,
    default: "__默认__",
  },
  showCell: {
    type: Boolean,
    default: true,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: "单位选择",
  },
});
const emits = defineEmits([
  "update:value",
  "update:visible",
  "update:label",
  "change",
]);

const valueModel = useVModel(props, "value", emits);
const labelModel =
  props.label === "__默认__" ? ref("") : useVModel(props, "label", emits);
const pickData = ref([]);

const visibleModel = isBoolean(props.visible)
  ? useVModel(props, "visible", emits)
  : ref(false);
const keywords = ref("");

const columns = ref([]);

const onPicker = () => {
  if (props.disabled) return;

  visibleModel.value = true;
};

const getColumns = async () => {
  const res = await getCompanyList({
    size: 10,
    current: 1,
    keywords: keywords.value,
  });
  // console.log("类别:", res);

  if (res?.data?.records) {
    columns.value = [
      res.data.records.map((item) => {
        return {
          label: item.name,
          value: item.id,
        };
      }),
    ];
  } else {
    columns.value = [];
  }
};

getColumns();

const debounceSearch = debounce(getColumns, 500);

function onPickerChange(e) {
  // console.log(e);
  valueModel.value = e;
  const key = e[0];
  labelModel.value = columns.value[0].find((item) => item.value === key).label;

  visibleModel.value = false;
  keywords.value = "";
  emits("change", {
    value: e,
    label: labelModel.value,
  });
}

function onDangerTypePickerCancel() {
  visibleModel.value = false;
  keywords.value = "";
}
</script>

<style lang="less" scoped></style>
